# -*- coding: UTF-8 -*-
import logging
import queue
import time
import json
import paho.mqtt.client as mqtt
from threading import Thread
from mysqltest.mysql_db import sqlconnect

# MQTT配置
MQTT_SERVER = "172.16.1.29"
MQTT_PORT = 18832
username = "intranet"
password = "gst@2024_123!"
topic = "IOT/intranet/client/request/prod/+"
publish_topic = "IOT/intranet/server/report/prod/"

# 共享队列（使用线程安全的Queue）
param_queue = queue.Queue()
param_queue1 = queue.Queue()
param_queue2 = queue.Queue()
param_queue3 = queue.Queue()

# 配置日志（仅需初始化一次）
logging.basicConfig(
  level=logging.INFO,
  format='%(asctime)s - %(levelname)s - %(message)s',
  handlers=[
    logging.FileHandler('server.log'),
    logging.StreamHandler()
  ]
)
log = logging.getLogger(__name__)


# 设备操作类（简化静态方法调用）
class ThreadPost:
  @staticmethod
  def audiostop_post():
    log.info("执行音频停止操作")

  @staticmethod
  def relay_post():
    log.info("执行继电器操作")

  @staticmethod
  def volume_post():
    log.info("执行音量调节操作")


class MQTTController:
  def __init__(self):
    self.keep_running = True
    self.client = mqtt.Client()
    self.callback_thread = None
    self.timers = {}  # 存储设备定时器 {imei: timer}

    # 初始化客户端
    self.client.username_pw_set(username, password)
    self.client.on_connect = self.on_connect
    self.client.on_message = self.on_message

  def on_connect(self, client, userdata, flags, rc):
    if rc == 0:
      log.info("成功连接到MQTT代理！已订阅主题：%s", topic)
      client.subscribe(topic)
    else:
      log.error(f"连接失败，错误码：{rc}")

  def on_message(self, client, userdata, message):
    """持续监测消息的核心回调"""
    try:
      msg = json.loads(message.payload.decode())
      log.info(f"收到消息: {msg} from {message.topic}")

      imei = msg.get('imei')
      param_queue.put(message.topic)
      param_queue1.put(msg.get('publishId'))
      param_queue2.put(imei)
      param_queue3.put(msg.get('cmd'))

    except Exception as e:
      log.error(f"消息处理错误: {str(e)}")

  def callback(self):
    """队列处理线程（持续运行）"""
    while self.keep_running:
      try:
        data = {
          'param': param_queue.get(timeout=1),
          'publishid': param_queue1.get(timeout=1),
          'imei': param_queue2.get(timeout=1),
          'cmd': param_queue3.get(timeout=1)
        }

        pub_topic = f"{publish_topic}{data['imei']}"
        response = {
          "cmd": "getDeviceBaseInfo",
          "imei": data['imei'],
          "publishId": 1,
          "result": "no such cmd",
          "resultId": 2,
          "topic": data['param']
        }

        self.client.publish(pub_topic, json.dumps(response))
        log.info(f"即时响应: {response}")

      except queue.Empty:
        continue
      except Exception as e:
        log.error(f"队列处理错误: {str(e)}")

  def start(self):
    """启动服务（仅执行一次）"""
    self.client.connect(MQTT_SERVER, MQTT_PORT, 60)
    self.client.loop_start()  # 启动MQTT网络循环（持续运行）

    # 启动队列处理线程
    self.callback_thread = Thread(target=self.callback, daemon=True)
    self.callback_thread.start()
    log.info("MQTT服务已启动，开始监听消息...")

  def stop(self):
    """停止服务（优雅关闭）"""
    self.keep_running = False
    self.client.loop_stop()
    self.client.disconnect()
    log.info("MQTT服务已停止")

def set_device_online():
  sql = "update device set run_status = 1 where device_name between 1 and 20"
  sql_result = sqlconnect.sqljudje(sql)
  sql1 = "select run_status from device where device_name = 20"
  sql_result1 = sqlconnect.sqljudje(sql1)
  print("打印当前设备在线状态：",sql_result1[0][0])
  try:
    if sql_result1 == 1:
      log.info("mock对象状态已更新为：在线")
  except Exception as e:
      log.info("CASE1： 断言异常", e)



def main():
  # 初始化MQTT控制器
  controller = MQTTController()

  try:
    # 设置设备状态（仅执行一次）
    set_device_online()

    # 启动MQTT服务（持续运行，无需循环）
    controller.start()

    # 保持主线程运行，避免退出
    #log.info("主进程运行中，按Ctrl+C停止服务...")
    while True:
      time.sleep(1)

  except KeyboardInterrupt:
    log.info("\n接收到中断信号，停止服务...")
    controller.stop()
  except Exception as e:
    log.error(f"主程序异常: {e}")
  finally:
    log.info("程序已安全退出")


